package hashcode;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashSet;

public class HashCodeTest {


    public static void main(String[] args) {
        User user1 = new User("张三", 15);
        User user2 = new User("张三", 16);
        HashSet<User> users = new HashSet<>();
        users.add(user1);
        System.out.println(users.contains(user2));

        // 三个string的hashcode相等
        String s1 = "fang";
        String s2 = "fang";
        String s3 = new String("fang");
        String s4 = new String("fang");
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s3.hashCode());
        System.out.println(s4.hashCode());
        // hashcode相等，但是==不等
        System.out.println(s3==s4);
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class User{
    private String name;
    private Integer age;


    @Override
    public boolean equals(Object o) {
        if(o == this)
            return true;
        if(!(o instanceof User))
            return false;
        if (o instanceof User) {
            User user = (User)o;
            return user.name.equals(name);
        }
        return false;
    }
    @Override
    public int hashCode() {
        int result = 17;
        result = result * 31 + name.hashCode();
//        result = result * 31 + age;

        return result;
    }
}
